import React, { Component } from 'react'
import axios from 'axios'
import PubSub from 'pubsub-js'

export default class Search extends Component {
  ref = React.createRef()
  search = () => {


    //  解构赋值value为keyWord
    const { current: {value: keyWord} } = this.ref;
    console.log(keyWord);

    // 发送请求前通知App更新状态
    // this.props.updateAppState({isFirst: false, isLoading: true })
    
    // 发送请求前通知List更新状态
    PubSub.publish('getGitHub', {isFirst: false, isLoading: true })

    // axios.get(`https://api.github.com/search/users?q=${keyWord}`)
    axios.get(`/api1/search/users?q=${keyWord}`)
        .then((response) => {
            console.log(response.data);
            // 请求成功后通知App更新状态 将上一次错误结果清空
            // this.props.updateAppState({ isLoading: false, users: response.data.items, err: '' })

            // 发送请求前通知List更新状态
            PubSub.publish('getGitHub', { isLoading: false, users: response.data.items, err: '' })
        })
        .catch(err => {
            console.log(err);

            // 请求失败后通知App更新状态
            // this.props.updateAppState({ isLoading: false, err: err.message })

            // 发送请求前通知List更新状态
            PubSub.publish('getGitHub', { isLoading: false, err: err.message })
        })
  }
  render() {
    return (
      <>
        <section className="jumbotron">
          <h3 className="jumbotron-heading">Search Github Users</h3>
          <div>
            <input
              ref={this.ref}
              type="text"
              placeholder="enter the name you search"
            />
            &nbsp;
            <button onClick={this.search}>Search</button>
          </div>
        </section>
      </>
    )
  }
}
